package dbutils02;

import org.apache.commons.dbcp2.BasicDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    /*私有构造方法 不可以在类外创建对象*/
    private JDBCUtils() {

    }
    private static BasicDataSource bs;
    /*注册驱动,当JDBCUtils类加载的时候,会执行静态代码块,此时会注册驱动*/
    static{
        Properties properties = new Properties();
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            //创建一个连接池
            bs = new BasicDataSource();
            //设置连接池的参数
            bs.setDriverClassName(properties.getProperty("driver"));
            bs.setUrl(properties.getProperty("url"));
            bs.setUsername(properties.getProperty("user"));
            bs.setPassword(properties.getProperty("password"));
            /*设置可选参数*/
            bs.setInitialSize(12);
            bs.setMaxTotal(12);
            bs.setMaxIdle(2);
            bs.setMinIdle(1);
            bs.setMaxWaitMillis(30000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*获取连接的静态方法*/
    public static Connection getConnection(){
        Connection conn = null;//提升作用域
        try {
            conn = bs.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    public static DataSource getDataSource(){
        return bs;
    }

}
